package com.shuwen.gcdj.service.basicsstructure;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuwen.gcdj.bean.AddResp;
import com.shuwen.gcdj.bean.DictResp;
import com.shuwen.gcdj.bean.VoidResp;
import com.shuwen.gcdj.bean.structure.request.*;
import com.shuwen.gcdj.bean.structure.response.InspectionItemTemplateResp;
import com.shuwen.gcdj.bean.structure.response.StructurePlanResp;
import com.shuwen.gcdj.bean.structure.response.StructureTreeResp;
import com.shuwen.gcdj.bean.structure.response.ThirdStructurePageResp;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.exception.ApiException;
import com.shuwen.gcdj.common.util.BeanHelper;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.entity.*;
import com.shuwen.gcdj.entity.basics.BasicsStrategy;
import com.shuwen.gcdj.mapper.mysql.*;
import com.shuwen.gcdj.service.BaseService;
import com.shuwen.gcdj.service.plan.PlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author :yys
 * @date : 2023/5/11 10:48
 */
@Slf4j
@Service
public class BasicsStructureService extends BaseService<BasicsStructureMapper, BasicsStructure> {

    @Autowired
    private BasicsStructureMapper basicsStructureMapper;

    @Autowired
    private PlanService planService;

    @Autowired
    private PlanMapper planMapper;

    @Autowired
    private PlanDetailMapper planDetailMapper;

    @Autowired
    private StrategyInspectionitemtemplaterelMapper strategyInspectionitemtemplaterelMapper;

    @Autowired
    private StrategyInspectionitemMapper strategyInspectionitemMapper;

    @Autowired
    private StrategyInspectionitemtemplateMapper strategyInspectionitemtemplateMapper;

    private static String errorMessage = "请填写完整参数";

    /**
     * 获取设备树形结构
     * @param req
     * @return
     */
    public List<StructureTreeResp> structureTree(StructureTreeReq req) {
        LambdaQueryWrapper<BasicsStructure> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BasicsStructure::getStrategyId,req.getStrategyId())
                .eq(BasicsStructure::getStructureType,req.getStructureType())
                .eq(BasicsStructure::getIsDelete,Constants.IS_DELETE_NORMAL);
//    获取所有设备
        List<BasicsStructure> basicsStructures = basicsStructureMapper.selectList(queryWrapper);
//        返回的结果集
        List<StructureTreeResp> structureTreeResps = new ArrayList<>();
//        复制集合
        List<StructureTreeResp> structureTreeRespsTo = BeanHelper.copyList(basicsStructures, StructureTreeResp.class);
//     存放一级设备
        for (StructureTreeResp bs : structureTreeRespsTo) {
            if (bs.getParentId().equals("0")) {
                structureTreeResps.add(bs);
            }
        }
//    开始递归
        for (StructureTreeResp structureTreeResp : structureTreeResps) {
            List<StructureTreeResp> pList = getChild(structureTreeResp.getId(),structureTreeRespsTo);
            structureTreeResp.setChildList(pList);
        }
        return structureTreeResps;
    }

//  递归
    private List<StructureTreeResp> getChild(String id,List<StructureTreeResp> list) {
        List<StructureTreeResp> childList = new ArrayList<>();
        for (StructureTreeResp powerItem : list) {
            if (powerItem.getParentId().equals(id)) {
                childList.add(powerItem);
            }
        }
        for (StructureTreeResp entity : childList) {
            entity.setChildList(getChild(entity.getId(), list));
        }
        if (CollectionUtils.isEmpty(childList)) {
            return new ArrayList<>();
        }
        return childList;
    }

    /**
     * 添加一级设备结构
     * @param initUserDto,structureFirstReq
     * @return
     */
    public AddResp addFirstStructure(InitUserDto initUserDto, StructureFirstReq structureFirstReq) {
        if(structureFirstReq == null || structureFirstReq.getStructureParamReq() == null || structureFirstReq.getPlanParamsReq() == null){
            throw new ApiException(errorMessage);
        }
        checkStructureFirstReqByStructureParamReq(structureFirstReq.getStructureParamReq());
        checkStructureFirstReqByPlanParamsReq(structureFirstReq.getPlanParamsReq());
//        添加一级设备
        BasicsStructure basicsStructure = new BasicsStructure();
        basicsStructure.setCreateId(initUserDto.getUserId());
        basicsStructure.setUpdateId(initUserDto.getUserId());
        BeanUtil.copyProperties(structureFirstReq.getStructureParamReq(),basicsStructure);
        basicsStructure.setId(null);
        int insert = basicsStructureMapper.insert(basicsStructure);
//        添加一级设备计划
        StrategyPlancycle strategyPlancycle = new StrategyPlancycle();
        strategyPlancycle.setCreateId(initUserDto.getUserId());
        strategyPlancycle.setUpdateId(initUserDto.getUserId());
        BeanUtil.copyProperties(structureFirstReq.getPlanParamsReq(),strategyPlancycle);
        strategyPlancycle.setId(null);
//        设置季计划
        if(!CollectionUtils.isEmpty(structureFirstReq.getPlanParamsReq().getSeason())){
            strategyPlancycle.setSeason(getDateList(structureFirstReq.getPlanParamsReq().getSeason()));
        }
//        设置年计划
        if(!CollectionUtils.isEmpty(structureFirstReq.getPlanParamsReq().getYearly())){
            strategyPlancycle.setYearly(getDateList(structureFirstReq.getPlanParamsReq().getYearly()));
        }
//        设置自定义计划
        if(!CollectionUtils.isEmpty(structureFirstReq.getPlanParamsReq().getCustomerDay())){
            strategyPlancycle.setCustomerDay(getDateList(structureFirstReq.getPlanParamsReq().getCustomerDay()));
        }
        strategyPlancycle.setStructureId(basicsStructure.getId());
        boolean save = planService.save(strategyPlancycle);
        if(insert < 1 || !save){
            throw new ApiException("添加一级设备结构失败");
        }
        AddResp addResp = new AddResp();
        addResp.setId(basicsStructure.getId());
        return addResp;
    }

    /**
     * 校验参数
     * @param planParamsReq
     */
    private void checkStructureFirstReqByPlanParamsReq(PlanParamsReq planParamsReq) {
        if(StringUtils.isEmpty(planParamsReq.getMaintenanceType())){
            throw new ApiException("保养类型不能为空");
        }
        if(StringUtils.isEmpty(planParamsReq.getStrategyId())){
            throw new ApiException("策略编号不能为空");
        }
    }

    /**
     * 校验参数
     * @param structureParamReq
     */
    private void checkStructureFirstReqByStructureParamReq(StructureParamReq structureParamReq) {
        if(StringUtils.isEmpty(structureParamReq.getName())){
            throw new ApiException("设备结构名称不能为空");
        }
        if(StringUtils.isEmpty(structureParamReq.getStrategyId())){
            throw new ApiException("策略编号不能为空");
        }
        if(StringUtils.isEmpty(structureParamReq.getParentId())){
            throw new ApiException("父结构编号不能为空");
        }
        if(StringUtils.isEmpty(structureParamReq.getDepth())){
            throw new ApiException("深度不能为空");
        }
        if(StringUtils.isEmpty(structureParamReq.getStructureType())){
            throw new ApiException("类型不能为空");
        }
        if(StringUtils.isEmpty(structureParamReq.getPersonnelId())){
            throw new ApiException("维保分派人员不能为空");
        }



    }

    /**
     * 添加二级设备结构
     * @param seCordStructureReq,initUserDto
     * @return
     */
    public AddResp addSeCordStructure(InitUserDto initUserDto,SeCordStructureReq seCordStructureReq) throws ParseException {
        if(seCordStructureReq == null || seCordStructureReq.getStructureParamReq() == null){
            throw new ApiException(errorMessage);
        }
//        校验参数
        checkStructureFirstReqByStructureParamReq(seCordStructureReq.getStructureParamReq());
//        添加二级设备
        BasicsStructure basicsStructure = new BasicsStructure();
        basicsStructure.setCreateId(initUserDto.getUserId());
        basicsStructure.setUpdateId(initUserDto.getUserId());
        BeanUtil.copyProperties(seCordStructureReq.getStructureParamReq(),basicsStructure);
        basicsStructure.setId(null);
        int insert = basicsStructureMapper.insert(basicsStructure);
        AddResp addResp = new AddResp();
        addResp.setId(basicsStructure.getId());
        if(insert < 1){
            throw new ApiException("添加二级设备结构失败");
        }
//        新增检查项模板关联表关联的二级部件id,检查项模板不为空（添加计划详情）
        if(!CollectionUtils.isEmpty(seCordStructureReq.getInsItemTemplateIds())){
            for (String s : seCordStructureReq.getInsItemTemplateIds()){
                LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(StrategyInspectionitemtemplaterel::getTemplateId,s)
                        .eq(StrategyInspectionitemtemplaterel::getStructureId,Constants.IS_TEMP + "")
                        .eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL);
                List<StrategyInspectionitemtemplaterel> strategyInspectionitemtemplaterelOne = strategyInspectionitemtemplaterelMapper.selectList(queryWrapper);
//                检查项模板不为空（添加计划详情）
                if(!CollectionUtils.isEmpty(strategyInspectionitemtemplaterelOne)){
                    BasicsStructure basicsStructureOne = basicsStructure.selectById(basicsStructure.getId());
//                    查计划
                    StrategyPlancycle strategyPlancycle = new StrategyPlancycle();
                    strategyPlancycle = strategyPlancycle.selectOne(new LambdaQueryWrapper<StrategyPlancycle>()
                            .eq(StrategyPlancycle::getIsDelete,Constants.IS_DELETE_NORMAL)
                            .eq(StrategyPlancycle::getStructureId,basicsStructureOne.getParentId()));
//                    是否开启模板
                    BasicsStrategy basicsStrategy = new BasicsStrategy();
                    basicsStrategy = basicsStrategy.selectOne(new LambdaQueryWrapper<BasicsStrategy>()
                            .eq(BasicsStrategy::getIsDelete,Constants.IS_DELETE_NORMAL)
                            .eq(BasicsStrategy::getId,basicsStructure.getStrategyId())
                            .eq(BasicsStrategy::getState,Constants.IS_ACTIVE_TEM));
                    if(basicsStrategy != null){
                        StrategyEquipmentstrategyrel strategyEquipmentstrategyrel = new StrategyEquipmentstrategyrel();
                        List<StrategyEquipmentstrategyrel> strategyEquipmentstrategyrelList = strategyEquipmentstrategyrel.selectList(new LambdaQueryWrapper<StrategyEquipmentstrategyrel>()
                                .eq(StrategyEquipmentstrategyrel::getIsDelete,Constants.IS_DELETE_NORMAL)
                                .eq(StrategyEquipmentstrategyrel::getStrategyId,basicsStructure.getStrategyId()));
                        for(StrategyEquipmentstrategyrel ss : strategyEquipmentstrategyrelList){
                            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(new Date());
                            calendar.add(Calendar.DAY_OF_MONTH,1);
                            String starTime = sd.format(calendar.getTime());
                            String endTime = planService.getmaxexecdatebystrategyid(ss.getEquipmentId());
                            if(endTime == null){
                                break;
                            }
                            List<String> dateList = getDateList(starTime, endTime);
//                            一级保养
                            if(strategyPlancycle.getMaintenanceType().equals(1)){
                                for(String date : dateList){
                                    insertPlanDetail(initUserDto,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.MEI);
                                }
                            }
//                            二级保养
                            if(strategyPlancycle.getMaintenanceType().equals(2)){
                                //                            周
                                Calendar c = Calendar.getInstance();
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                if(!StringUtils.isEmpty(strategyPlancycle.getWeekly())){
                                    for(String date : dateList){
                                        c.setTime(simpleDateFormat.parse(date));
                                        String weekday = c.get(Calendar.DAY_OF_WEEK)+"";
                                        if(strategyPlancycle.getWeekly().contains(weekday)){
                                            insertPlanDetail(initUserDto,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.WEEKLY);
                                        }

                                    }
                                }
//                            月
                                if(!StringUtils.isEmpty(strategyPlancycle.getMonthly())){
                                    for(String date : dateList){
                                        c.setTime(simpleDateFormat.parse(date));
                                        String weekday = c.get(Calendar.DAY_OF_MONTH)+"";
                                        if(strategyPlancycle.getMonthly().contains(weekday)){
                                            insertPlanDetail(initUserDto,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.MONTHLY);
                                        }

                                    }
                                }
//                            季
                                if(!StringUtils.isEmpty(strategyPlancycle.getSeason())){
                                    for(String date : dateList){
                                        if(strategyPlancycle.getSeason().contains(getDateStr(date))){
                                            insertPlanDetail(initUserDto,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.SEASON);
                                        }

                                    }
                                }
//                            年
                                if(!StringUtils.isEmpty(strategyPlancycle.getYearly())){
                                    for(String date : dateList){
                                        if(strategyPlancycle.getYearly().contains(getDateStr(date))){
                                            insertPlanDetail(initUserDto,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.YEARLY);
                                        }

                                    }
                                }
//                            自定义天
                                if(!StringUtils.isEmpty(strategyPlancycle.getCustomerDay())){
                                    for(String date : dateList){
                                        if(strategyPlancycle.getCustomerDay().contains(getDateStr(date))){
                                            insertPlanDetail(initUserDto,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.CUSTOMER_DAY);
                                        }

                                    }
                                }
//                            隔天执行
                                if(!StringUtils.isEmpty(strategyPlancycle.getEveryDay())){
                                    int i = 0;
                                    for(String date : dateList){

                                        if(i == 0){
                                            insertPlanDetail(initUserDto,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.EVERY_DAY);
                                            i++;
                                            continue;
                                        }
                                        if(i == strategyPlancycle.getEveryDay()+1){
                                            insertPlanDetail(initUserDto,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.EVERY_DAY);
                                            i = 1;
                                        }else{
                                            i++;
                                        }

                                    }
                                }
                            }
                        }
                    }

                }
                for(StrategyInspectionitemtemplaterel si : strategyInspectionitemtemplaterelOne){
                    si.setId(null);
                    si.setUpdateId(initUserDto.getUserId());
                    si.setCreateId(initUserDto.getUserId());
                    si.setStructureId(basicsStructure.getId());
                    strategyInspectionitemtemplaterelMapper.insert(si);
                }

            }
        }
        return addResp;
    }

    public void insertPlanDetail(InitUserDto initUserDto,BasicsStructure basicsStructureOne,StrategyEquipmentstrategyrel ss,String s,String date,StrategyPlancycle strategyPlancycle,Integer planCycleType){
        StrategyPlandetail strategyPlandetail = new StrategyPlandetail();
        strategyPlandetail.setCreateId(initUserDto.getUserId());
        strategyPlandetail.setUpdateId(initUserDto.getUserId());
        strategyPlandetail.setFirstStructureId(basicsStructureOne.getParentId());
        strategyPlandetail.setSecondStructureId(basicsStructureOne.getId());
        strategyPlandetail.setEquipmentId(ss.getEquipmentId());
        strategyPlandetail.setPlanCycleType(planCycleType);
        strategyPlandetail.setUserId(basicsStructureOne.getPersonnelId());
        strategyPlandetail.setMajor(basicsStructureOne.getStructureType());
        strategyPlandetail.setItemTempId(s);
        strategyPlandetail.setExecDate(date);
        strategyPlandetail.setStrategyId(basicsStructureOne.getStrategyId());
        strategyPlandetail.setMaintenanceType(strategyPlancycle.getMaintenanceType());
        strategyPlandetail.setPlancycleId(strategyPlancycle.getId());
        planDetailMapper.insert(strategyPlandetail);
    }

    /**
     * 编辑一级设备结构（编辑计划）
     * @param initUser
     * @param structureFirstReq
     * @return
     */
    public VoidResp editFirstStructure(InitUserDto initUser, StructureFirstReq structureFirstReq) {
        if(structureFirstReq == null || structureFirstReq.getStructureParamReq() == null || structureFirstReq.getPlanParamsReq() == null){
            throw new ApiException(errorMessage);
        }
        if(StringUtils.isEmpty(structureFirstReq.getStructureParamReq().getId())){
            throw new ApiException("id不能为空");
        }
        BasicsStructure byId = basicsStructureMapper.selectById(structureFirstReq.getStructureParamReq().getId());
        if(byId == null){
            throw new ApiException("一级设备结构不存在！");
        }
        checkStructureFirstReqByStructureParamReq(structureFirstReq.getStructureParamReq());
        checkStructureFirstReqByPlanParamsReq(structureFirstReq.getPlanParamsReq());
//        编辑一级设备
        byId.setUpdateId(initUser.getUserId());
        BeanUtil.copyProperties(structureFirstReq.getStructureParamReq(),byId);
        byId.setUpdateTime(null);
        basicsStructureMapper.updateById(byId);
//        编辑一级设备计划
        if(StringUtils.isEmpty(structureFirstReq.getPlanParamsReq().getId())){
            throw new ApiException("id不能为空");
        }
        StrategyPlancycle planById = planService.getById(structureFirstReq.getPlanParamsReq().getId());
        if(planById == null){
            throw new ApiException("一级设备结构绑定的计划不存在！");
        }
        planById.setUpdateId(initUser.getUserId());
        BeanUtil.copyProperties(structureFirstReq.getPlanParamsReq(),planById);
        planById.setUpdateTime(null);
//        设置季计划
        if(!CollectionUtils.isEmpty(structureFirstReq.getPlanParamsReq().getSeason())){
            if(planById.getSeason().equals(structureFirstReq.getPlanParamsReq().getSeason().toString())){
                planById.setSeason(structureFirstReq.getPlanParamsReq().getSeason().toString()
                        .replace("[","")
                        .replace("]",""));
            }else{
                planById.setSeason(getDateList(structureFirstReq.getPlanParamsReq().getSeason()));
            }
        }
//        设置年计划
        if(!CollectionUtils.isEmpty(structureFirstReq.getPlanParamsReq().getYearly())){
            if(planById.getYearly().equals(structureFirstReq.getPlanParamsReq().getYearly().toString())){
                planById.setYearly(structureFirstReq.getPlanParamsReq().getYearly().toString()
                        .replace("[","")
                        .replace("]",""));
            }else{
                planById.setYearly(getDateList(structureFirstReq.getPlanParamsReq().getYearly()));
            }
        }
//        设置自定义计划
        if(!CollectionUtils.isEmpty(structureFirstReq.getPlanParamsReq().getCustomerDay())){
            if(planById.getCustomerDay().equals(structureFirstReq.getPlanParamsReq().getCustomerDay().toString())){
                planById.setCustomerDay(structureFirstReq.getPlanParamsReq().getCustomerDay().toString()
                        .replace("[","")
                        .replace("]",""));
            }else{
                planById.setCustomerDay(getDateList(structureFirstReq.getPlanParamsReq().getCustomerDay()));
            }
        }
        planService.updateById(planById);
        return new VoidResp();
    }

    /**
     * 编辑二级设备结构（编辑三级设备）
     * @param initUser
     * @param req
     * @return
     */
    public VoidResp editSeCordStructure(InitUserDto initUser, OperateReq req) throws ParseException{
     if(req == null || StringUtils.isEmpty(req.getStructureId()) || StringUtils.isEmpty(req.getName())){
         throw new ApiException("二级结构参数不完整！");
     }
//     删除
     for(String s : req.getDelTemplateIds()){
         LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.eq(StrategyInspectionitemtemplaterel::getStructureId,req.getStructureId())
                 .eq(StrategyInspectionitemtemplaterel::getTemplateId,s)
                 .eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL);
         List<StrategyInspectionitemtemplaterel> oneList = strategyInspectionitemtemplaterelMapper.selectList(queryWrapper);
//         删除对应计划详情
         LambdaQueryWrapper<StrategyPlandetail> queryWrapperOne = new LambdaQueryWrapper<>();
         queryWrapperOne.eq(StrategyPlandetail::getIsDelete,Constants.IS_DELETE_NORMAL)
                 .eq(StrategyPlandetail::getItemTempId,s);
         List<StrategyPlandetail> strategyPlandetails = planDetailMapper.selectList(queryWrapperOne);
         for(StrategyPlandetail sp : strategyPlandetails){
             sp.setIsDelete(Constants.IS_DELETE_YES);
             sp.setUpdateId(initUser.getUserId());
             sp.setUpdateTime(null);
             planDetailMapper.updateById(sp);
         }
         for(StrategyInspectionitemtemplaterel strategyInspectionitemtemplaterel : oneList){
             strategyInspectionitemtemplaterel.setUpdateTime(null);
             strategyInspectionitemtemplaterel.setUpdateId(initUser.getUserId());
             strategyInspectionitemtemplaterel.setIsDelete(Constants.IS_DELETE_YES);
             strategyInspectionitemtemplaterelMapper.updateById(strategyInspectionitemtemplaterel);
         }
     }
//     添加
        for(String s : req.getAddTemplateIds()){
            LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StrategyInspectionitemtemplaterel::getStructureId,Constants.IS_TEMP + "")
                    .eq(StrategyInspectionitemtemplaterel::getTemplateId,s)
                    .eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL);
            List<StrategyInspectionitemtemplaterel> oneList = strategyInspectionitemtemplaterelMapper.selectList(queryWrapper);
//         添加对应计划详情
            if(!CollectionUtils.isEmpty(oneList)){
                BasicsStructure basicsStructureOne = basicsStructureMapper.selectById(req.getStructureId());
//                    查计划
                StrategyPlancycle strategyPlancycle = new StrategyPlancycle();
                strategyPlancycle = strategyPlancycle.selectOne(new LambdaQueryWrapper<StrategyPlancycle>()
                        .eq(StrategyPlancycle::getIsDelete,Constants.IS_DELETE_NORMAL)
                        .eq(StrategyPlancycle::getStructureId,basicsStructureOne.getParentId()));
//                    是否开启模板
                BasicsStrategy basicsStrategy = new BasicsStrategy();
                basicsStrategy = basicsStrategy.selectOne(new LambdaQueryWrapper<BasicsStrategy>()
                        .eq(BasicsStrategy::getIsDelete,Constants.IS_DELETE_NORMAL)
                        .eq(BasicsStrategy::getId,basicsStructureOne.getStrategyId())
                        .eq(BasicsStrategy::getState,Constants.IS_ACTIVE_TEM));
                if(basicsStrategy != null){
                    StrategyEquipmentstrategyrel strategyEquipmentstrategyrel = new StrategyEquipmentstrategyrel();
                    List<StrategyEquipmentstrategyrel> strategyEquipmentstrategyrelList = strategyEquipmentstrategyrel.selectList(new LambdaQueryWrapper<StrategyEquipmentstrategyrel>()
                            .eq(StrategyEquipmentstrategyrel::getIsDelete,Constants.IS_DELETE_NORMAL)
                            .eq(StrategyEquipmentstrategyrel::getStrategyId,basicsStructureOne.getStrategyId()));
                    for(StrategyEquipmentstrategyrel ss : strategyEquipmentstrategyrelList){
                        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new Date());
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        String starTime = sd.format(calendar.getTime());
                        String endTime = planService.getmaxexecdatebystrategyid(ss.getEquipmentId());
                        if(endTime == null){
                            break;
                        }
                        List<String> dateList = getDateList(starTime, endTime);
//                            一级保养
                        if(strategyPlancycle.getMaintenanceType().equals(1)){
                            for(String date : dateList){
                                insertPlanDetail(initUser,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.MEI);
                            }
                        }
//                            二级保养
                        if(strategyPlancycle.getMaintenanceType().equals(2)){
                            //                            周
                            Calendar c = Calendar.getInstance();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            if(!StringUtils.isEmpty(strategyPlancycle.getWeekly())){
                                for(String date : dateList){
                                    c.setTime(simpleDateFormat.parse(date));
                                    String weekday = c.get(Calendar.DAY_OF_WEEK)+"";
                                    if(strategyPlancycle.getWeekly().contains(weekday)){
                                        insertPlanDetail(initUser,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.WEEKLY);
                                    }

                                }
                            }
//                            月
                            if(!StringUtils.isEmpty(strategyPlancycle.getMonthly())){
                                for(String date : dateList){
                                    c.setTime(simpleDateFormat.parse(date));
                                    String weekday = c.get(Calendar.DAY_OF_MONTH)+"";
                                    if(strategyPlancycle.getMonthly().contains(weekday)){
                                        insertPlanDetail(initUser,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.MONTHLY);
                                    }

                                }
                            }
//                            季
                            if(!StringUtils.isEmpty(strategyPlancycle.getSeason())){
                                for(String date : dateList){
                                    if(strategyPlancycle.getSeason().contains(getDateStr(date))){
                                        insertPlanDetail(initUser,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.SEASON);
                                    }

                                }
                            }
//                            年
                            if(!StringUtils.isEmpty(strategyPlancycle.getYearly())){
                                for(String date : dateList){
                                    if(strategyPlancycle.getYearly().contains(getDateStr(date))){
                                        insertPlanDetail(initUser,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.YEARLY);
                                    }

                                }
                            }
//                            自定义天
                            if(!StringUtils.isEmpty(strategyPlancycle.getCustomerDay())){
                                for(String date : dateList){
                                    if(strategyPlancycle.getCustomerDay().contains(getDateStr(date))){
                                        insertPlanDetail(initUser,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.CUSTOMER_DAY);
                                    }

                                }
                            }
//                            隔天执行
                            if(!StringUtils.isEmpty(strategyPlancycle.getEveryDay())){
                                int i = 0;
                                for(String date : dateList){

                                    if(i == 0){
                                        insertPlanDetail(initUser,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.EVERY_DAY);
                                        i++;
                                        continue;
                                    }
                                    if(i == strategyPlancycle.getEveryDay()+1){
                                        insertPlanDetail(initUser,basicsStructureOne,ss,s,date,strategyPlancycle,Constants.EVERY_DAY);
                                        i = 1;
                                    }else{
                                        i++;
                                    }

                                }
                            }
                        }
                    }
                }

            }
            for(StrategyInspectionitemtemplaterel inspectionitemtemplaterel : oneList){
                StrategyInspectionitemtemplaterel tem = new StrategyInspectionitemtemplaterel();
                tem.setStructureId(req.getStructureId());
                tem.setInspectionItemId(inspectionitemtemplaterel.getInspectionItemId());
                tem.setUpdateId(initUser.getUserId());
                tem.setCreateId(initUser.getUserId());
                tem.setTemplateId(s);
                strategyInspectionitemtemplaterelMapper.insert(tem);
            }
        }
        return new VoidResp();
    }

    /**
     * 批量删除一级设备结构
     * @param initUser
     * @param ids
     * @return
     */
    public VoidResp batchFirstStructure(InitUserDto initUser, DeleteFirstStructure ids) {
        for(String s : ids.getIds()){
            BasicsStructure byId = basicsStructureMapper.selectById(s);
            if(byId == null){
                throw new ApiException("一级设备结构不存在");
            }
//            获取一级，二级设备
            LambdaQueryWrapper<BasicsStructure> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BasicsStructure::getId,s)
                        .or()
                        .eq(BasicsStructure::getParentId,s)
                    .eq(BasicsStructure::getIsDelete,Constants.IS_DELETE_NORMAL);
            List<BasicsStructure> basicsStructures = basicsStructureMapper.selectList(queryWrapper);
            for (BasicsStructure basicsStructure : basicsStructures){
//                删除检查项模板关联表
                if(basicsStructure.getDepth().equals(0)){
                    LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapperOne = new LambdaQueryWrapper<>();
                    queryWrapperOne.eq(StrategyInspectionitemtemplaterel::getStructureId,basicsStructure.getId())
                            .eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL);
                    List<StrategyInspectionitemtemplaterel> sList = strategyInspectionitemtemplaterelMapper.selectList(queryWrapperOne);
                    for(StrategyInspectionitemtemplaterel st : sList){
                        st.setIsDelete(Constants.IS_DELETE_YES);
                        st.setUpdateTime(null);
                        st.setUpdateId(initUser.getUserId());
                        strategyInspectionitemtemplaterelMapper.updateById(st);
                    }
                }else{
//                删除一级设备绑定的计划
                    LambdaQueryWrapper<StrategyPlancycle> queryWrapperone = new LambdaQueryWrapper<>();
                    queryWrapperone.eq(StrategyPlancycle::getStructureId,basicsStructure.getId())
                            .eq(StrategyPlancycle::getIsDelete,Constants.IS_DELETE_NORMAL);
                    List<StrategyPlancycle> strategyPlancycles = planMapper.selectList(queryWrapperone);
                    for(StrategyPlancycle stt : strategyPlancycles){
                        stt.setIsDelete(Constants.IS_DELETE_YES);
                        stt.setUpdateId(initUser.getUserId());
                        stt.setUpdateTime(null);
                        planMapper.updateById(stt);
                    }
                }
//                删除一级，二级设备
                basicsStructure.setIsDelete(Constants.IS_DELETE_YES);
                basicsStructure.setUpdateId(initUser.getUserId());
                basicsStructure.setUpdateTime(null);
                basicsStructureMapper.updateById(basicsStructure);
            }
        }
        return new VoidResp();
    }

    /**
     * 批量删除二级设备结构
     * @param initUser
     * @param ids
     * @return
     */
    public VoidResp batchSeCordStructure(InitUserDto initUser, DeleteFirstStructure ids) {
        for(String s : ids.getIds()){
            BasicsStructure byId = basicsStructureMapper.selectById(s);
            if(byId == null){
                throw new ApiException("二级设备结构不存在");
            }
            LambdaQueryWrapper<BasicsStructure> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BasicsStructure::getId,s)
                    .eq(BasicsStructure::getDepth,1)
                    .eq(BasicsStructure::getIsDelete,Constants.IS_DELETE_NORMAL);
            List<BasicsStructure> basicsStructures = basicsStructureMapper.selectList(queryWrapper);
            for (BasicsStructure basicsStructure : basicsStructures){
//                删除检查项模板关联表
                LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapperOne = new LambdaQueryWrapper<>();
                queryWrapperOne.eq(StrategyInspectionitemtemplaterel::getStructureId,basicsStructure.getId())
                        .eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL);
                List<StrategyInspectionitemtemplaterel> sList = strategyInspectionitemtemplaterelMapper.selectList(queryWrapperOne);
                for(StrategyInspectionitemtemplaterel st : sList){
                    st.setIsDelete(Constants.IS_DELETE_YES);
                    st.setUpdateTime(null);
                    st.setUpdateId(initUser.getUserId());
                    strategyInspectionitemtemplaterelMapper.updateById(st);
                }
//                删除二级设备
                basicsStructure.setIsDelete(Constants.IS_DELETE_YES);
                basicsStructure.setUpdateId(initUser.getUserId());
                basicsStructure.setUpdateTime(null);
                basicsStructureMapper.updateById(basicsStructure);
            }
        }
        return new VoidResp();
    }

    /**
     * 获取一级结构绑定计划
     * @param id
     * @return
     */
    public StructurePlanResp structureByPlan(String id) {
        if(StringUtils.isEmpty(id)){
            throw new ApiException("一级部件id不能为空");
        }
        LambdaQueryWrapper<StrategyPlancycle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrategyPlancycle::getStructureId,id)
                .eq(StrategyPlancycle::getIsDelete,Constants.IS_DELETE_NORMAL);
        StrategyPlancycle one = planService.getOne(queryWrapper);
        if(one == null){
            return new StructurePlanResp();
        }
        StructurePlanResp structurePlanResp = new StructurePlanResp();
        BeanUtil.copyProperties(one,structurePlanResp);
        return structurePlanResp;
    }

    /**
     * 获取三级结构分页信息
     * @param req
     * @return
     */
    public Page<ThirdStructurePageResp> getThirdStructurePage(ThirdStructurePageReq req) {
//        一级设备
      if(req.getDepth().equals(Constants.STR_ONE)){
          LambdaQueryWrapper<BasicsStructure> queryWrapper = new LambdaQueryWrapper<>();
          queryWrapper.eq(BasicsStructure::getParentId,req.getStructureId())
                  .eq(BasicsStructure::getIsDelete,Constants.IS_DELETE_NORMAL);
          List<BasicsStructure> list = basicsStructureMapper.selectList(queryWrapper);
          List<String> strings = new ArrayList<>();
          for(BasicsStructure s : list){
              strings.add(s.getId());
          }
          if(CollectionUtils.isEmpty(strings)){
              return new Page<>();
          }
          return getThirdStructureList(strings,req);
      }else{
//      二级设备
          List<String> strings = new ArrayList<>();
          strings.add(req.getStructureId());
          return getThirdStructureList(strings,req);
      }
    }

    /**
     *
     * @param ids 二级id集合
     * @param req
     * @return
     */
    private Page<ThirdStructurePageResp> getThirdStructureList(List<String> ids,ThirdStructurePageReq req) {
        Page<ThirdStructurePageResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
        IPage<ThirdStructurePageResp> allList = strategyInspectionitemMapper.getPage(page,ids,Constants.STRATEGY_INSPECTIONITEM_RESULT,Constants.STRATEGY_INSPECTIONITEM_DISPOSAL_METHOD);
        List<ThirdStructurePageResp> res = allList.getRecords();
        Page<ThirdStructurePageResp> resPage = new Page<>(page.getCurrent(), page.getSize(), allList.getTotal());
        resPage.setRecords(res);
        return resPage;
    }

    /**
     * 根据二级结构id获取检查项模板信息
     * @param id
     * @return
     */
    public List<InspectionItemTemplateResp> getFirstStructure(String id) {
//        获取所有模板
       List<InspectionItemTemplateResp> list = strategyInspectionitemtemplateMapper.getAllList();
//       获取选中模板
        LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrategyInspectionitemtemplaterel::getStructureId,id)
                .eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL)
                .groupBy(StrategyInspectionitemtemplaterel::getTemplateId);
        List<StrategyInspectionitemtemplaterel> ckList = strategyInspectionitemtemplaterelMapper.selectList(queryWrapper);
        for(InspectionItemTemplateResp i : list){
            for(StrategyInspectionitemtemplaterel s : ckList){
                if(i.getId().equals(s.getTemplateId())){
                    i.setChecked(true);
                }
            }
        }
        return list;
    }

    /**
     * 获取三级结构列表信息
     * @param req
     * @return
     */
    public List<ThirdStructurePageResp> getThirdStructure(ThirdStructurePageReq req) {
//        一级设备
        if(req.getDepth().equals(Constants.STR_ONE)){
            LambdaQueryWrapper<BasicsStructure> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BasicsStructure::getParentId,req.getStructureId())
                    .eq(BasicsStructure::getIsDelete,Constants.IS_DELETE_NORMAL);
            List<BasicsStructure> list = basicsStructureMapper.selectList(queryWrapper);
            List<String> strings = new ArrayList<>();
            for(BasicsStructure s : list){
                strings.add(s.getId());
            }
            if(CollectionUtils.isEmpty(strings)){
                return new ArrayList<>();
            }
            return strategyInspectionitemMapper.getThirdStructure(strings,Constants.STRATEGY_INSPECTIONITEM_RESULT,Constants.STRATEGY_INSPECTIONITEM_DISPOSAL_METHOD);
        }else{
//      二级设备
            List<String> strings = new ArrayList<>();
            strings.add(req.getStructureId());
            return strategyInspectionitemMapper.getThirdStructure(strings,Constants.STRATEGY_INSPECTIONITEM_RESULT,Constants.STRATEGY_INSPECTIONITEM_DISPOSAL_METHOD);
        }

    }

    /**
     * 获取结构类型
     * @return
     */
    public List<DictResp> getstategytemplatelist() {
        LambdaQueryWrapper<SysDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictionary::getParentCode,Constants.BASICS_STRUCTURE_TYPE)
                .eq(SysDictionary::getState,Constants.IS_ACTIVE_TEM)
                .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL);
        SysDictionary sysDictionary = new SysDictionary();
        List<SysDictionary> sysDictionaries = sysDictionary.selectList(queryWrapper);
        return BeanHelper.copyList(sysDictionaries, DictResp.class);
    }

    /**
     * 获取一级部件结构配置信息
     * @return
     */
    public List<DictResp> getbasicsstructurefirstnamelist() {
        LambdaQueryWrapper<SysDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictionary::getParentCode,Constants.BASICS_STRUCTURE_FIRST_NAME)
                .eq(SysDictionary::getState,Constants.IS_ACTIVE_TEM)
                .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL);
        SysDictionary sysDictionary = new SysDictionary();
        List<SysDictionary> sysDictionaries = sysDictionary.selectList(queryWrapper);
        return BeanHelper.copyList(sysDictionaries, DictResp.class);
    }

    /**
     * 获取二级部件结构配置信息
     * @return
     */
    public List<DictResp> getbasicsstructuresecondnamelist() {
        LambdaQueryWrapper<SysDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictionary::getParentCode,Constants.BASICS_STRUCTURE_SECOND_NAME)
                .eq(SysDictionary::getState,Constants.IS_ACTIVE_TEM)
                .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL);
        SysDictionary sysDictionary = new SysDictionary();
        List<SysDictionary> sysDictionaries = sysDictionary.selectList(queryWrapper);
        return BeanHelper.copyList(sysDictionaries, DictResp.class);
    }
}
